package com.appspot.bibtable.view.html;

import java.lang.reflect.Field;

import com.appspot.bibtable.model.Reference;
import com.appspot.bibtable.model.annotation.AttributeValue;
import com.appspot.bibtable.model.annotation.Input;
import com.appspot.bibtable.util.HtmlUtility;

public class ReferenceInputTable extends ReferenceTable
{
	@Override
	protected String getValue(Reference reference, Field field, Input input)
	{
		AttributeValue name = input.name();
		AttributeValue[] values = input.values();
		String assignedValue = reference.getValue(field);

		StringBuilder builder = new StringBuilder();
		switch (input.type())
		{
			case SINGLE_LINE_TEXT:
			{
				String element = String.format("<input type=\"text\" name=\"%s\" value=\"%s\" class=\"reference-field\" />", name.attribute(), (assignedValue == null ? values[0].attribute() : assignedValue));
				builder.append(element);
			}
				break;
			case MULTILINE_TEXT:
				builder.append("<textarea name=\"" + name.attribute() + "\" class=\"reference-field\">");
				builder.append(assignedValue == null ? values[0].attribute() : assignedValue.toString());
				builder.append("</textarea>");
				break;
			case READONLY_TEXT:
				builder.append(HtmlUtility.encode(reference.getValue(field)));
				break;
			case COMBOBOX:
				builder.append("<select name=\"" + name.attribute() + "\" class=\"reference-field\">");
				for (int index = 0; index < values.length; index++)
				{
					if (values[index].attribute().equals(assignedValue))
					{
						builder.append("<option value=\"" + values[index].attribute() + "\" selected=\"selected\">");
					}
					else
					{
						builder.append("<option value=\"" + values[index].attribute() + "\">");
					}
					builder.append(values[index].display());
					builder.append("</option>");
				}
				builder.append("</select>");
				break;
		}
			
		return builder.toString();
	}
}
